using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using PluginZoombieInterface;
using PluginMapInterface;
using System.IO;
using System.Reflection;
using System.Media;
using System.Xml;


namespace XNAGame_Lab1
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        //        List<MyXNAButton> myButton = new List<MyXNAButton>();
        Map map;
        //        Zoombie animal;
        //      int nMyButton;
        List<Zoombie> button;
        List<Zoombie> buttonB;
        Sun sun;
        MyText2D text;
        MyText2D pg;
        List<MyText2D> abouttext;//danh cac about text
        MapWithCell mapcell;
        Store myStores;
        //   Zoombie right;
        Zoombie duahau;
        HP HP;
        HP HpZoombie;
        List<Zoombie> zbStone;
        List<MapFrame> mapicon;
        MapFrame iconclose;
        Charactor charactor;
        public enum State { not, newgame, about, option, quit, shop, chooseMap,close,win }
        State state;
        //Store store;
        Form formMap;
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            this.IsMouseVisible = true;
            graphics.PreferredBackBufferWidth = 1000;
            graphics.PreferredBackBufferHeight = 600;
        }
        List<IPlugin> plugStone = new List<IPlugin>();

        List<IPlugin> plugMg = new List<IPlugin>();


        List<IPluginMap> plugMap = new List<IPluginMap>();
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }
        public int RandomValue(int x, int y)
        {
            Random rd = new Random();
            int t = rd.Next(x, y);
            return t;
        }
        public Vector2 RandomVector()
        {
            int temp = RandomValue(0, mapcell.nCol);
            Vector2 t = mapcell.Cell[11, temp].TopLeft;
            return t;
        }
        Shirt sh;
        Hat hat;

        #region"load plugin zoombie"
        List<IPlugin> LoadZoombiePlugin(string path)
        {
            List<IPlugin> plug = new List<IPlugin>();
            //   plugMg.Clear();
            Assembly asm;
            Type[] types;
            string[] files = Directory.GetFiles(System.Windows.Forms.Application.StartupPath + path, "*.ext");
            foreach (string f in files)
            {
                asm = Assembly.LoadFile(f);
                types = asm.GetTypes();
                string className = Path.GetFileNameWithoutExtension(f) + ".PluginClass";
                foreach (Type type in types)
                {
                    if (type.FullName == className)
                    {
                        IPlugin exPl = (IPlugin)Activator.CreateInstance(type);
                        plug.Add(exPl);
                    }
                }
            }
            return plug;
        }
        #endregion

        #region"load plugin map"
        List<IPluginMap> LoadMapPlugin(string path)
        {
            List<IPluginMap> plug = new List<IPluginMap>();
            //plugMg.Clear();
            Assembly asm;
            Type[] types;
            string[] files = Directory.GetFiles(System.Windows.Forms.Application.StartupPath + path, "*.ext");
            foreach (string f in files)
            {
                asm = Assembly.LoadFile(f);
                types = asm.GetTypes();
                string className = Path.GetFileNameWithoutExtension(f) + ".PluginClass";
                foreach (Type type in types)
                {
                    if (type.FullName == className)
                    {
                        IPluginMap exPl = (IPluginMap)Activator.CreateInstance(type);
                        plug.Add(exPl);
                    }
                }
            }
            return plug;
        }
        #endregion

        //bool bPress=false;
        //List<SpriteMenu> sprites;
        //int nsprite = 1;
        Form backgroundmenu;
        List<MapFrame> itemMenu;//danh sach cac tuy chon tren man hinh
        List<string> item2;
        List<string> item1;
        Form aboutFrame;
        SpriteFont fontAbout;
        SpriteFont Font1;
        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {

            Font1 = Content.Load<SpriteFont>("font");
            fontAbout = Content.Load<SpriteFont>("about");
            itemMenu = new List<MapFrame>();
            string url = "menu1.xml";
            
          
            #region"load menu"
            state = State.not;
            item1 = XMLProccess(url);
            item2 = XMLProccess("menu2.xml");
            char[] s = { ',' };
            char[] c = { '-' };
            for (int i = 0; i < item1.Count; i++)
            {
                string[] str = item1[i].Split(c);
                string[] strsize = str[1].Split(s);
                MapFrame itMenu = new MapFrame(Content, str[0], 1, new Vector2(int.Parse(strsize[0]), int.Parse(strsize[1])), new Vector2(200, 100), str[2]);
                itMenu.Click += new EventHandler(itMenu_Click);
                itemMenu.Add(itMenu);
            }
            #endregion

            List<string> textAbout = XMLProccess("about.xml");
            
            CreateFormAbout(fontAbout, textAbout);
            aboutFrame = new Form(Content, "Background\\khung", new Vector2(200, 0), new Vector2(600, 600));

            backgroundmenu = new Form(Content, "Background\\background_menu", new Vector2(0, 0), new Vector2(800, 600));
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            mapicon = new List<MapFrame>();


            plugMap = LoadMapPlugin("\\addons\\map");
            for (int i = 0; i < plugMap.Count; i++)
            {
                //khung hinh chu nhat ban do 
                MapFrame icon = new MapFrame(Content, plugMap[i].GetBitmap()[0], 1, new Vector2(71 + i * 174, 83), new Vector2(147, 210), i.ToString());
                mapicon.Add(icon);
                icon.Click += new EventHandler(icon_Click);
            }
            formMap = new Form(Content, "formmap/loadmap", new Vector2(0, 0), new Vector2(800, 509));
            button = new List<Zoombie>();
            string textname = "0";

            text = new MyText2D(Content, textname, Font1, new Vector2(150, 43), Color.Black);

            InitObject(  Font1);

        }

        private void InitObject(SpriteFont Font1)
        {
            myStores = new Store();
            // TODO: use this.Content to load your game content here
            #region"khoi tao map "
            string[] strCellTexture = new string[60];
            for (int i = 0; i < 60; i++)
                strCellTexture[i] = "Cell/frame03";
            int nRow = 12;
            int nCol = 5;
            int[,] cell = new int[12, 5];
            int k = 0;
            for (int i = 0; i < nRow; i++)
                for (int j = 0; j < nCol; j++)
                {
                    cell[i, j] = k++;

                }
            mapcell = new MapWithCell(Content, strCellTexture, 12 * 5, 12, 5, cell, new Vector2(100, 150), new Vector2(66, 72));


            #endregion
            //khoi tao cac cuc cua moi ben 

            #region "doc danh sach quai tu plugin va load len "
            plugMg = LoadZoombiePlugin("\\addons\\zoombie");
            for (int i = 0; i < plugMg.Count; i++)
            {
                MyXNAStore store10 = new MyXNAStore(Content, plugMg[i].GetBitmap()[3], 1, new Vector2(i * 60 + 255, 5), new Vector2(65, 65));
                myStores.Add(store10);
            }
            #endregion
            #region "khoi tao quai cua doi phuong"
            buttonB = new List<Zoombie>();
            //Load het hinh cho khoi bi lac
            for (int i = 0; i < plugMg.Count; i++)
            {
                duahau = new Zoombie(Content, plugMg[i].GetBitmapBack()[0], plugMg[i].numMove(), new Vector2(800, 232), new Vector2(50, 50), 0, null, plugMg[i].getName(),
                        (int)plugMg[i].getDef(), (int)plugMg[i].getDam(), (int)plugMg[i].getHp(), new ZoombieBack());
            }

            duahau = new Zoombie(Content, plugMg[0].GetBitmapBack()[0], plugMg[0].numMove(), new Vector2(800, 232), new Vector2(50, 50), 0, null, plugMg[0].getName(),
                        (int)plugMg[0].getDef(), (int)plugMg[0].getDam(), (int)plugMg[0].getHp(), new ZoombieBack());
            buttonB.Add(duahau);

            #endregion

            iconclose = new MapFrame(Content, "background/close", 1, new Vector2(200, 0), new Vector2(60, 60), "close");
            iconclose.Click += new EventHandler(iconclose_Click);


            Song backgroundsong;
            backgroundsong = Content.Load<Song>("audio\\city_bg");
            MediaPlayer.Play(backgroundsong);

            MediaPlayer.IsRepeating = true;

            //  sound.PlayLooping();
            //sound.Play();
            pg = new MyText2D(Content, plugMg[0].getName(), Font1, new Vector2(150, 80), Color.Black);
            HP = new HP(Content, "HP/hp", 1, new Vector2(2, 0), new Vector2(77, 77), 2000);
            HpZoombie = new HP(Content, "HP/hp", 1, new Vector2(920, 0), new Vector2(77, 77), 2000);

            sun = new Sun(Content, "Sun/Skull-icon", 1, new Vector2(175, 30), new Vector2(100, 100));
            //su dung mau Decorade de them cac do vat cho nhan vat trong game
            charactor = new Charactor(Content, "Plugin/Charactor/Avatar/body/body", 1, new Vector2(20, 120), new Vector2(50, 50));
            sh = new Shirt(charactor, Content, "Plugin/Charactor/Avatar/head/head", 1, charactor.TopLeft, new Vector2(50, 50));
            hat = new Hat(charactor, Content, "Plugin/Charactor/Avatar/hat/hat", 1, charactor.TopLeft, new Vector2(50, 50));
        }
        #region "tao form "
        /// <summary>
        /// tao form bat ky 
        /// </summary>
        /// <param name="fontAbout">font </param>
        /// <param name="textAbout">danh sach text</param>
        private void CreateFormAbout(SpriteFont fontAbout, List<string> textAbout)
        {
            abouttext = new List<MyText2D>();
            abouttext.Add(new MyText2D(Content, textAbout[0], fontAbout, new Vector2(300, 40), Color.White));
            for (int i = 1; i < textAbout.Count; i++)
            {
                abouttext.Add(new MyText2D(Content, textAbout[i], fontAbout, new Vector2(250, 30 * i + 150), Color.White));

            }
        }
        #endregion
        void iconclose_Click(object sender, EventArgs e)
        {
            state = State.not;
        }

        void itMenu_Click(object sender, EventArgs e)
        {
            MapFrame n = (MapFrame)sender;
            string v = n.Name;
            if (v.Equals("newgame"))
            {
                InitObject(Font1);
                state = State.newgame;
            }
            if (v.Equals("about"))
            {
                state = State.about;
                List<string> textAbout = XMLProccess("about.xml");

                CreateFormAbout(fontAbout, textAbout);
            }
            if (v.Equals("option"))
            { 

                state = State.option;
                List<string> textAbout = XMLProccess("waiting.xml");

                CreateFormAbout(fontAbout, textAbout);

            }
            if (v.Equals("quit"))
            {
                state = State.quit;

                Exit();
            }
            if (v.Equals("shop"))
            {
                state = State.shop;
                List<string> textAbout = XMLProccess("waiting.xml");

                CreateFormAbout(fontAbout, textAbout);

            }

        }
        #region "doc file xml"
        private List<string> XMLProccess(string url)
        {
            XmlTextReader reader = new XmlTextReader(url);
            //
            ReadXML xml = new ReadXML();
            List<string> item = xml.AddElement(reader);
            return item;
        }
        #endregion
        #region "su kien click tren menu "
        void icon_Click(object sender, EventArgs e)
        {
            //  for (int i = 0; i < mapicon.Count;i++ )
            //     if((MyXNAButton) sender==mapicon[i])

            MouseState msT = Mouse.GetState();
            for (int l = 0; l < mapicon.Count; l++)
            {
                if (mapicon[l].isClicked(new Vector2(msT.X, msT.Y)))
                {
                    state = State.chooseMap;
                    map = new Map(Content, plugMap[l].GetBitmap()[1], new Vector2(0, 0), new Vector2(1000, 600));
                    isMap = true;
                    #region "khoi tao da chinh giua"
                    zbStone = new List<Zoombie>();
                    plugStone = LoadZoombiePlugin("\\addons\\stone");
                    for (int i = 0; i < mapcell.nRow; i++)
                        for (int j = 0; j < mapcell.nCol; j++)
                            if (i == 5 || i == 6)
                            {
                                for (int k = 0; k < plugStone.Count; k++)
                                    if (plugMap[l].getStone().Equals(plugStone[k].getName()))
                                    {
                                        Zoombie btn11 = new Zoombie(Content, plugStone[k].GetBitmap()[0], plugStone[k].numMove(),
                                            mapcell.Cell[i, j].TopLeft, new Vector2(50, 50), 4, sun, plugStone[k].getName(),
                                            (int)plugStone[k].getDef(), (int)plugStone[k].getDam(), (int)plugStone[k].getHp(),
                                            new ZoombieNomal());
                                        zbStone.Add(btn11);
                                        numberMap = k;
                                        break;
                                    }
                            }


                    #endregion
                    break;
                }
            }

            //throw new NotImplementedException();
        }
        #endregion



        float t = 0;// time counter
        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }
        int dem = 0;
        float Rx = 50.0f;
        float Ry = 50.0f;
        MyXNAStore temp = null;
        int numberMap = -1;
        int flag = 0;

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {

            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            KeyboardState kbState = Keyboard.GetState();
            MouseState msState = Mouse.GetState();

            if (state == State.about||state == State.option||state == State.shop||state==State.close||state==State.win)
            {
                iconclose.Update(gameTime);
            }
                if (state == State.not )
                {
                    for (int i = 0; i < itemMenu.Count; i++)
                    {
                        char[] s = { ',' };
                        char[] c = { '-' };


                        if (itemMenu[i].isClicked(new Vector2(msState.X, msState.Y)))
                        {
                            string[] str = item2[i].Split(c);//cat duong dan
                            string[] strsize = item2[1].Split(s);//cat toa do 
                            //                        List < string>  st =new List<string>();
                            //st.Add(str[0]);
                            // new MapFrame(Content, str[0], 1, new Vector2(int.Parse(strsize[0]),int.Parse( strsize[1])), new Vector2(200, 100));

                            itemMenu[i].UpdateImg(Content, str[0], 1, itemMenu[i].TopLeft, itemMenu[i].Size);
                            itemMenu[i].Update(gameTime);
                            break;
                        }
                        else
                        {
                            string[] str = item1[i].Split(c);//cat duong dan
                            string[] strsize = item1[1].Split(s);//cat toa do 
                            //                        List < string>  st =new List<string>();
                            //st.Add(str[0]);
                            // new MapFrame(Content, str[0], 1, new Vector2(int.Parse(strsize[0]),int.Parse( strsize[1])), new Vector2(200, 100));

                            itemMenu[i].UpdateImg(Content, str[0], 1, itemMenu[i].TopLeft, itemMenu[i].Size);
                            //                        break;
                        }
                    }


            }
            if (state == State.newgame)
            {

                for (int i = 0; i < mapicon.Count; i++)

                    mapicon[i].Update(gameTime);
                formMap.Update(gameTime);
                // this.Draw(gameTime);
            }
            if (state == State.chooseMap)
            {
                HpZoombie.Update(gameTime);
                map.Update(gameTime);
                //button.Update(gameTime);
                mapcell.Update(gameTime);
                UpdateHP();        //HP.Update(gameTime);
                sun.Update(gameTime);
                for (int i = 0; i < button.Count; i++)
                {
                    button[i].Update(gameTime);
                }
                for (int i = 0; i < buttonB.Count; i++)
                {
                    buttonB[i].Update(gameTime);
                }
                

                myStores.Update(gameTime);
                for (int i = 0; i < myStores.ListZoombie.Count; i++)
                    if (myStores.ListZoombie[i].isClicked(new Vector2(msState.X, msState.Y)))
                    {
                        temp = myStores.ListZoombie[i];
                        if (sun.Cost < temp.Cost)

                            temp = null;
                        break;
                    }
                text.Text = sun.Cost.ToString();
                //myStores.Cost = sun.Cost;
                text.Update(gameTime);
                //right.Update(gameTime);
                duahau.Update(gameTime);
                charactor.Update(gameTime);
                sh.Update(gameTime);
                hat.Update(gameTime);

                #region "xem xet va cham cua cac con trong b"
                isAttackLeftRight(buttonB);
                isAttackLeftRight(button);
                // else
                //{
                for (int i = button.Count - 1; i >= 0; i--)
                {
                    Zoombie zbi = button[i];
                    int hh = 0;
                    hh = CollideNode(zbi, hh, zbStone);
                    if (buttonB.Count == 0 && hh == 0)//neu ko con zombieback va ko dung cuc da
                    {

                        if (!zbi.Strategy.iSAttack(zbi.TopLeft))//neu chua toi bien
                        {
                            if (zbi.Fmove == 0)//cho di
                                zbi.Fmove = 3;
                            zbi.Move += new EventHandler(zbi_Move);
                        }
                    }
                    else
                    {
                        int tmp = 0;
                        tmp = CollideNode(zbi, tmp, buttonB);//xem co dung con Zoombie nao ko?
                        if (tmp == 0)//neu ko dung Zoombie
                        {
                            tmp = CollideNode(zbi, tmp, zbStone);//Xem co dung da ko?
                        }
                        if (tmp == 0 && zbi.Fmove == 0)//neu ko dung da
                        {
                            if (!zbi.Strategy.iSAttack(zbi.TopLeft))//neu chua toi bien

                                zbi.Fmove = 3;//di
                            //zbi.Flag = 0;
                        }
                    }
                    zbi.Update(gameTime);

                }

                #endregion
                #region"ghi chu "
                /*Vector2 ufo = m.UnknowVar;
            Vector2 vufo = myBTN.TopLeft;
            float mLeft = vufo.X / 2;
            float mRight = vufo.Y / 2;
            Vector2 mPosition = new Vector2(mLeft, mRight);
            if (kbState.IsKeyDown(Keys.Left))
            {
                ufo.X -= 10;
                mPosition.X -= 10;
            }
            if (kbState.IsKeyDown(Keys.Right))
            {

                ufo.X += 10;
                mPosition.X += 10;
            }
            if (kbState.IsKeyDown(Keys.Up))
            {
                ufo.Y -= 10;
                mPosition.Y -= 10;

            }
            if (kbState.IsKeyDown(Keys.Down))
            {
                ufo.Y += 10;
                mPosition.Y += 10;

            }
            m.UnknowVar = ufo;
            myBTN.TopLeft = mPosition;
            if (kbState.IsKeyDown(Keys.Escape))
                this.Exit();
            m.Update(gameTime);
            //myBTN.Update(gameTime);
            //    MouseState msState = Mouse.GetState();
            */
                /*          int idx = -1;
                          if (msState.LeftButton == ButtonState.Pressed)
                          {

                              Vector2 point = new Vector2(msState.X, msState.Y);
                              for (int i = 0; i < nMyButton; i++)
                              {
                                  if (myButton[i].isClicked(point))
                                  {
                                      idx = i;
                                      //MyXNAButton xna = myButton[idx];

                                      //                        Console.WriteLine(i);
                                      break;
                                  }
                              }
                          }
                          switch (idx)
                          {
                              case 0:
                                  List<string> str1 = new List<string>();
                                  str1.Add("start2");
                                  MyXNAButton xna = myButton[idx];
                                  xna = new MyXNAButton(Content, str1, str1.Count, xna.TopLeft, xna.Size);
                                  myButton[idx] = xna;
                                  //                    nMyButton--;

                                  //       vtA.X = myButton[idx].TopLeft.X;
                                  //      vtA.Y = myButton[idx].TopLeft.Y;
                                  break;
                          }
                          /*   Vector2 vtA = new Vector2();
                             switch (idx)
                             { 
                                 case 0: 
                                     //myButton[idx] .TopLeft= new Vector2( 100f, 100f);\
                                     vtA.X= myButton[idx].TopLeft.X;
                                     vtA.Y = myButton[idx].TopLeft.Y;
                                     break;
                             }*/
                /*        for (int i = 0; i < nMyButton; i++)
                        {
                            myButton[i].Update(gameTime);
                            /*    Vector2 pos = myButton[i].TopLeft;
                             //phuong trinh duong tron
                            //y=ax+b 
                          * x-xa/yb-ya = y-ya/yb-ya
                          * x= 
                          * //x = a + r cos(t)
                             //y = b + r sin(t).
                             pos.X =(float) (100.0f + Rx * Math.Sin(t/100.0f));

                            pos.Y =(float) (100.0f + Ry * Math.Cos(t/100.0f));
               //              sprites[i].Position = pos;
                            myButton[i].TopLeft = pos;
                             */
                /*      }
                      t++;
                      //            Rx += 0.1f;
                      //          Ry += 0.1f;

                      // TODO: Add your update logic here

                      base.Update(gameTime);
                 */
                #endregion
            }
        }
        #region "cap nhat hp"
        private void UpdateHP()
        {
            if (sun.Cost % 10 == 0)
            {

                dem++;
                //bun.UpdateImg(Content, plugMg[3].GetBitmap()[1], plugMg[3].numAttack(), bun.TopLeft, bun.Size);
                

                if (dem % 20 == 0)
                {
                    int tm = RandomValue(0, plugMg.Count);
                    Vector2 rd = RandomVector();
                    Zoombie duahau3 = new Zoombie(Content, plugMg[tm].GetBitmapBack()[0], plugMg[tm].numMove(), rd, new Vector2(50, 50), 0, null, plugMg[tm].getName(),
                        (int)plugMg[tm].getDef(), (int)plugMg[tm].getDam(), (int)plugMg[tm].getHp(), new ZoombieBack());
                    buttonB.Add(duahau3);
                }


            }

        }
        #endregion
        private void isAttackLeftRight(List<Zoombie> lst)
        {
            for (int i = 0; i < lst.Count; i++)
            {
                if (lst[i].Strategy.iSAttack(lst[i].TopLeft))
                {
                    lst[i].Fmove = 0;
                    //chut sua lai -- tru hp co loi thi vo day bo cai nay
                    List<string> vl = new List<string>();
                    if (lst == buttonB)
                    {
                        vl.Add("HP/HP" + (10 - (Math.Round((decimal)HP.HPChar * 10 / HP.HPStart))).ToString("00"));
                        HP.UpdateImg(Content, vl, vl.Count, HP.TopLeft);
                        HP.HPChar -= lst[i].Damp * 2 / 3;
                    }
                    else
                    {
                        vl.Add("HP/HP" + (10 - (Math.Round((decimal)HpZoombie.HPChar * 10 / HpZoombie.HPStart))).ToString("00"));
                        HpZoombie.UpdateImg(Content, vl, vl.Count, HpZoombie.TopLeft);
                        HpZoombie.HPChar -= lst[i].Damp * 2 / 3;
                    }
                    if (HP.HPChar <= 0)
                    {
                        
                        HP.HPChar = 2000;
                        state = State.close;
                        List<string> textAbout = XMLProccess("lose.xml");
                        CreateFormAbout(fontAbout, textAbout);

                    }
                    if (HpZoombie.HPChar <= 0)
                    {
                        HpZoombie.HPChar = 2000;
                        state = State.win;
                        List<string> textAbout = XMLProccess("win.xml");
                        CreateFormAbout(fontAbout, textAbout);

                    }
                    lst[i].Attack += new EventHandler(Game1_Attack);
                }
                else
                {
                    if (lst == buttonB)
                    {
                        int count = -1;
                        for (int j = 0; j < button.Count; j++)
                            if (lst[i].isCollide(new Vector2(button[j].TopLeft.X, button[j].TopLeft.Y), new Vector2(10, 10)))
                            {
                                count = 1;
                                lst[i].Fmove = 0;
                                lst[i].Attack += new EventHandler(Game1_Attack);
                            }
                        if (count == -1 && lst[i].Fmove == 0)
                            lst[i].Fmove = 3;
                    }

                    lst[i].Move += new EventHandler(Game1_Move);
                }
                //    Zoombie zb = (Zoombie)button[i];
                //    //               if (zb.isCollide(right))
                //    //text.Text = "da bi dung";

            }
        }

        private int CollideNode(Zoombie zbi, int tmp, List<Zoombie> lst)
        {
            int ismove = 0;
            for (int j = lst.Count - 1; j >= 0; j--)
                if (zbi.isCollide(new Vector2(lst[j].TopLeft.X, lst[j].TopLeft.Y), new Vector2(10, 10)))
                {
                    if (zbStone.Count > 0 && lst[j].Name.Equals(zbStone[0].Name))
                    {
                        //dung cuc da chinh giua
                        lst[j].UpdateImg(Content, plugStone[numberMap].GetBitmap()[1], 1, lst[j].TopLeft, lst[j].Size);
                    }
                    //zbi.Flag = 1;
                    tmp = 1;
                    zbi.Fmove = 0;

                    zbi.Attack += new EventHandler(zbi_Attack);

                    if (zbi.HP < 1)
                    {
                        button.Remove(zbi);
                        lst[j].Fmove = 3;
                        lst[j].Move += new EventHandler(Game1_Move);

                        break;
                    }
                    else
                    {
                        lst[j].Fmove = 0;
                        zbi.HP -= lst[j].Damp;
                    }
                    //buttonB[j].Flag = 1;

                    if (lst[j].HP < 1)
                    {
                        lst.Remove(lst[j]);
                        zbi.Flag = 1;
                        //zbi.Fmove = 3;
                        //zbi.Move+=new EventHandler(zbi_Move);
                    }
                    else
                    {
                        lst[j].HP -= zbi.Damp;
                        lst[j].Attack += new EventHandler(Game1_Attack);
                    }
                    //                bun.State = MyXNAButton.ButtonStatus.attack;
                    //      bun.Update(gameTime);
                    break;
                }
                else
                {
                    if (ismove == 0)
                    {
                        zbi.Move += new EventHandler(zbi_Move);
                        ismove = 1;
                    }
                    //zbi.Flag = 0;
                }
            return tmp;
        }

        void Game1_Attack(object sender, EventArgs e)
        {
            Zoombie zb = (Zoombie)sender;

            if (zb.Strategy.Name.Equals("back"))
            {
                int tmp = getPosZoombie(zb);
                if (tmp != -1)
                    zb.UpdateImg(Content, plugMg[tmp].GetBitmapBack()[1], plugMg[tmp].numAttack(), zb.TopLeft, zb.Size);
            }
            else
                zbi_Attack(sender, e);
        }

        void Game1_Move(object sender, EventArgs e)
        {
            Zoombie zb = (Zoombie)sender;
            for (int i = 0; i < buttonB.Count; i++)
            {
                if (zb.Equals(buttonB[i]))
                {
                    int tmp = getPosZoombie(zb);
                    if (tmp != -1)
                        zb.UpdateImg(Content, plugMg[tmp].GetBitmapBack()[0], plugMg[tmp].numMove(), zb.TopLeft, zb.Size);
                    break;
                }
            }
        }

        void zbi_Move(object sender, EventArgs e)
        {
            Zoombie zb = (Zoombie)sender;
            int tmp = getPosZoombie(zb);
            if (tmp != -1)
                zb.UpdateImg(Content, plugMg[tmp].GetBitmap()[0], plugMg[tmp].numMove(), zb.TopLeft, zb.Size);

        }

        private int getPosZoombie(Zoombie zb)
        {
            int tmp = -1;
            for (int i = 0; i < plugMg.Count; i++)
            {
                if (zb.Name.Equals(plugMg[i].getName()))
                {
                    tmp = i;
                    break;
                }
            }
            return tmp;
        }

        void zbi_Attack(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
            Zoombie zb = (Zoombie)sender;
            int tmp = getPosZoombie(zb);
            if (tmp != -1)
            {
                zb.UpdateImg(Content, plugMg[tmp].GetBitmap()[1], plugMg[tmp].numAttack(), zb.TopLeft, zb.Size);
            }

        }



        void zb_Attack(object sender, EventArgs e)
        {
            Zoombie tmp = (Zoombie)sender;


            //throw new NotImplementedException();
        }
        bool isMap = false;
        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        /// 
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            if (state == State.not)
            {

                mainBackground(gameTime);

            }
            if (state == State.option||state == State.shop||state==State.close||state==State.win)
            {
                DrawForm(gameTime);
            }
            if (state == State.about)
            {
                DrawForm(gameTime);
            }
            if (state == State.newgame)
            {
                formMap.Draw(gameTime, spriteBatch);
                for (int i = 0; i < mapicon.Count; i++)
                    mapicon[i].Draw(gameTime, spriteBatch);
            }
            if (state == State.chooseMap)
            {
                map.Draw(gameTime, spriteBatch);
                mapcell.Draw(gameTime, spriteBatch);
                myStores.Draw(gameTime, spriteBatch);

                #region "su kien click tren ban do "
                if (temp != null)
                {
                    switch (temp.State)
                    {
                        case MyXNAStore.ButtonStatus.Normal:


                            //spriteBatch.Draw(texture, bounds, Color.White);
                            break;
                        case MyXNAStore.ButtonStatus.MouseOver:
                            for (int i = 0; i < 12; i++)
                                for (int j = 0; j < 5; j++)
                                    if (mapcell.Cell[i, j].isClicked(new Vector2(temp.PreviousState.X, temp.PreviousState.Y)) && i >= 0 && i <= 2)
                                    {//+ previousState.X - 25

                                        int tmp = getZoombieInStore();

                                        Zoombie btn11 = new Zoombie(Content, plugMg[tmp].GetBitmap()[0], plugMg[tmp].numMove(), new Vector2(mapcell.Cell[i, j].TopLeft.X, mapcell.Cell[i, j].TopLeft.Y), new Vector2(50, 50), 4, sun, plugMg[tmp].getName(), (int)plugMg[tmp].getDef(), (int)plugMg[tmp].getDam(), (int)plugMg[tmp].getHp(), new ZoombieNomal());



                                        if (btn11.Cost < sun.Cost)
                                        {
                                            sun.Cost -= btn11.Cost;
                                            //                                    sun.Update(gameTime);

                                            //mapcell.Cell[i, j] = new Cell(Content, "Cell/frame01", mapcell.Cell[i, j].TopLeft, mapcell.Cell[i, j].Size);
                                            //   mapcell.Cell[i, j].Update(gameTime);
                                            button.Add(btn11);
                                        }
                                        temp.State = MyXNAStore.ButtonStatus.Normal;

                                        mapcell.Cell[i, j] = new Cell(Content, "Cell/frame03", mapcell.Cell[i, j].TopLeft, mapcell.Cell[i, j].Size);
                                        //break;
                                    }
                                    else
                                        mapcell.Cell[i, j] = new Cell(Content, "Cell/frame03", mapcell.Cell[i, j].TopLeft, mapcell.Cell[i, j].Size);
                            ///spriteBatch.Draw(hoverTexture, bounds, Color.White);
                            break;
                        case MyXNAStore.ButtonStatus.Pressed:
                            int tm = getZoombieInStore();
                            MyXNAButton btn2 = new MyXNAButton(Content, plugMg[tm].GetBitmap()[0], plugMg[tm].numMove(), new Vector2(temp.PreviousState.X, temp.PreviousState.Y), new Vector2(50, 50));
                            btn2.Draw(gameTime, spriteBatch);

                            for (int i = 0; i < 12; i++)
                                for (int j = 0; j < 5; j++)
                                    if (mapcell.Cell[i, j].isClicked(new Vector2(temp.PreviousState.X, temp.PreviousState.Y)))
                                    {//+ previousState.X - 25
                                        //mau xanh 
                                        if (i >= 0 && i <= 2)
                                        {
                                            mapcell.Cell[i, j] = new Cell(Content, "Cell/frame01", mapcell.Cell[i, j].TopLeft, mapcell.Cell[i, j].Size);
                                        }

                                        //                                break;
                                    }
                                    else
                                        //trong suot
                                        mapcell.Cell[i, j] = new Cell(Content, "Cell/frame00", mapcell.Cell[i, j].TopLeft, mapcell.Cell[i, j].Size);
                            for (int u = 3; u < 12; u++)
                                for (int v = 0; v < 5; v++)
                                    mapcell.Cell[u, v] = new Cell(Content, "Cell/frame02", mapcell.Cell[u, v].TopLeft, mapcell.Cell[u, v].Size);

                            break;
                        default:
                            break;
                    }
                }
                #endregion
                #region "ghi chu quan trong"
                //if (temp != null)
                //{
                //    switch (temp.State)
                //    {
                //        case MyXNAButton.ButtonStatus.Normal:


                //            //spriteBatch.Draw(texture, bounds, Color.White);
                //            break;
                //        case MyXNAButton.ButtonStatus.MouseOver:
                //            for (int i = 0; i < 12; i++)
                //                for (int j = 0; j < 5; j++)
                //                    if (mapcell.Cell[i, j].isClicked(new Vector2(temp.PreviousState.X, temp.PreviousState.Y)))
                //                    {//+ previousState.X - 25


                //                        Zoombie btn11 = new Zoombie(Content, "thu", 15, new Vector2(mapcell.Cell[i, j].TopLeft.X, mapcell.Cell[i, j].TopLeft.Y), new Vector2(50, 50),4,sun);
                //                        if (btn11.Cost < sun.Cost)
                //                        {
                //                            sun.Cost -= btn11.Cost;
                //                            //                                    sun.Update(gameTime);

                //                            //mapcell.Cell[i, j] = new Cell(Content, "Cell/frame01", mapcell.Cell[i, j].TopLeft, mapcell.Cell[i, j].Size);
                //                            //   mapcell.Cell[i, j].Update(gameTime);
                //                            button.Add(btn11);
                //                        }
                //                        temp.State = MyXNAButton.ButtonStatus.not;

                //                        mapcell.Cell[i, j] = new Cell(Content, "Cell/frame03", mapcell.Cell[i, j].TopLeft, mapcell.Cell[i, j].Size);
                //                        //break;
                //                    }
                //                    else
                //                        mapcell.Cell[i, j] = new Cell(Content, "Cell/frame03", mapcell.Cell[i, j].TopLeft, mapcell.Cell[i, j].Size);
                //            ///spriteBatch.Draw(hoverTexture, bounds, Color.White);
                //            break;
                //        case MyXNAButton.ButtonStatus.Pressed:

                //            MyXNAButton btn2 = new MyXNAButton(Content, "thu", 1, new Vector2(temp.PreviousState.X, temp.PreviousState.Y), new Vector2(50, 50));
                //            btn2.Draw(gameTime, spriteBatch);

                //            for (int i = 0; i < 12; i++)
                //                for (int j = 0; j < 5; j++)
                //                    if (mapcell.Cell[i, j].isClicked(new Vector2(temp.PreviousState.X, temp.PreviousState.Y)))
                //                    {//+ previousState.X - 25

                //                        mapcell.Cell[i, j] = new Cell(Content, "Cell/frame01", mapcell.Cell[i, j].TopLeft, mapcell.Cell[i, j].Size);

                //                        //                                break;
                //                    }
                //                    else
                //                        mapcell.Cell[i, j] = new Cell(Content, "Cell/frame00", mapcell.Cell[i, j].TopLeft, mapcell.Cell[i, j].Size);

                //            //spriteBatch.Draw(pressedTexture, bounds, Color.White);
                //            break;
                //        default:
                //            // spriteBatch.Draw(texture, bounds, Color.White);
                //            break;
                //    }
                //}
                #endregion


                text.Draw(gameTime, spriteBatch);
                sun.Draw(gameTime, spriteBatch);
                pg.Draw(gameTime, spriteBatch);
                HP.Draw(gameTime, spriteBatch);

                HpZoombie.Draw(gameTime, spriteBatch);
                for (int j = 0; j < zbStone.Count; j++)
                    zbStone[j].Draw(gameTime, spriteBatch);
                for (int i = 0; i < button.Count; i++)
                    button[i].Draw(gameTime, spriteBatch);
                for (int i = 0; i < buttonB.Count; i++)
                    buttonB[i].Draw(gameTime, spriteBatch);
                charactor.Draw(gameTime, spriteBatch);
                sh.Draw(gameTime, spriteBatch);
                hat.Draw(gameTime, spriteBatch);
                base.Draw(gameTime);
            }

        }

        private void DrawForm(GameTime gameTime)
        {
            mainBackground(gameTime);
            aboutFrame.Draw(gameTime, spriteBatch);
            for (int i = 0; i < abouttext.Count; i++)

                abouttext[i].Draw(gameTime, spriteBatch);
            iconclose.Draw(gameTime, spriteBatch);
        }

        private void mainBackground(GameTime gameTime)
        {
            backgroundmenu.Draw(gameTime, spriteBatch);
            for (int i = 0; i < itemMenu.Count; i++)
                itemMenu[i].Draw(gameTime, spriteBatch);
        }

        private int getZoombieInStore()
        {
            int tmp = 0;
            for (int k = 0; k < myStores.ListZoombie.Count; k++)
            {
                if (temp == myStores.ListZoombie[k])
                    tmp = k;
            }
            return tmp;
        }

    }
}


